import { getCode, outLogin, register, login, getUserInfo } from "@/api/index";
import { setToken, removeToken } from "../../untils/token";
const state = {
  Code: "",
  userInfo: {},
  token: localStorage.getItem("token"),
};
const mutations = {
  //设置验证码
  setCode(state, data) {
    state.Code = data;
  },
  //设置用户信息
  setUserInfo(state, data) {
    state.userInfo = data;
  },
  //设置token
  setToken(state, data) {
    state.token = data;
  },
  //清除token
  clear(state) {
    (state.token = ""), (state.userInfo = {});
  },
};
const actions = {
  //获取验证码
  async getCode({ commit }, phone) {
    //发起请求
    const res = await getCode(phone);
    if (res.code == 200) {
      commit("setCode", res.data);
      return "ok";
    } else {
      return Promise.reject(new Error("失败！"));
    }
  },
  //注册
  async register({ commit }, data) {
    const res = await register(data);
    if (res.code == 200) return "注册成功！";
    return Promise.reject(new Error("注册失败！手机号已经被注册"));
  },
  //登录
  async login({ commit }, data) {
    const res = await login(data);
    if (res.code == 200) {
      //保存token
      commit("setToken", res.data.token);
      // localStorage.setItem("token", res.data.token);
      setToken(res.data.token);
      return "ok";
    } else {
      return Promise.reject(new Error("登录失败！"));
    }
  },
  //获取用户信息
  async getUserInfo({ commit }, data) {
    const res = await getUserInfo({ data });
    if (res.code == 200) {
      commit("setUserInfo", res.data);
    }
  },
  //退出登录
  async outLogin({ commit }) {
    const res = await outLogin();
    if (res.code == 200) {
      commit("clear");
      removeToken();
      return "ok";
    } else {
      return Promise.resolve(new Error("退出失败！"));
    }
  },
};
const getters = {};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
